
function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}

var u = navigator.userAgent;
if (u.indexOf('iPhone') > -1) {   //苹果手机
    setupWebViewJavascriptBridge(function(bridge) {
        bridge.registerHandler('testJSFunction', function(data, responseCallback) {
            //alert('JS方法被调用:'+data);
            responseCallback('js执行过了');
        })
    });
}


//localStorage.appToken='e2920d0c8a98f51c99411769eb2751d3';
var indexPage=1,num=0;

/* IOS方法 */
function getTokenIos() {
    WebViewJavascriptBridge.callHandler('getToken', {'foo': 'bar'}, function(response) {
        //alert('扫描结果:' + response);
        localStorage.appToken=response;
        appToken=response;
        return response
    })
}


/* 安卓手机 */
function getToken() {
    var response=jsObj.getPartCode();
    // alert(response)
    response=JSON.parse(response);
    appToken=response.token;
    appUserId=response.userId;
    localStorage.appToken=appToken;
    localStorage.appUserId=appUserId;
    return response
}

//停机类型
function getDataStopType() {
    var url='/equipment/newVersion/listStopType';
    var mdObj=md5Fun(appUserId,url,appToken);
    $.ajax({
        type: "POST",
        timeout : 5000,
        url: webUrlCon+url,
        beforeSend: function(request) {
            //request.setRequestHeader("Content-Type", "application/json");
            request.setRequestHeader("sequence", mdObj.sequence);
            request.setRequestHeader("nonceStr", mdObj.nonceStr);
            request.setRequestHeader("userId", appUserId);
            request.setRequestHeader("token",appToken);
            //xmlhttp.setRequestHeader("infName", url);
            //xmlhttp.setRequestHeader("osVersion", '');
            request.setRequestHeader("versionType", "0");
            request.setRequestHeader("osPlatform", mdObj.osPlatform);
            request.setRequestHeader("appVersion", mdObj.appVersion);
            request.setRequestHeader("sign", mdObj.sign);
        },
        success: function (data) {
            if(data.code==100){
                var content=data.content
                var stopHtml='';
                for(var i=0;content.length>i;i++){
                    if(content[i].name.length>7){
                        stopHtml+='<li class="plural" data-id="'+content[i].id+'"><span>'+content[i].name+'</span></li>';
                    }else{
                        stopHtml+='<li data-id="'+content[i].id+'"><span>'+content[i].name+'</span></li>';
                    }
                }
                if(stopHtml!=''){
                    $('.searchType ul').html(stopHtml);
                }else {
                    $('.searchType ul').html('<li><span>暂无数据</span></li>');
                }
            }else{
                //fundebug.notify("equipment/searchRecord接口返回数据", JSON.stringify(data));
               layer.open({
                   content: data.message
                    ,btn: '确定'
                });
            }
        },
        error: function(e) {
            /*layer.open({
                content: '无法请求服务器，请稍后再试！'
                ,btn: '确定'
            });*/
        }
    });
}

function typeClass(type) {
    if(type=='保养停机'){
        return 'maintenance';
    }
    else if(type=='待单停机') {
        return 'staySingle';
    }
    else if(type=='待料停机') {
        return 'reliable';
    }
    else if(type=='工艺停机') {
        return 'process';
    }
    else if(type=='故障停机') {
        return 'malfunction';
    }
    else if(type=='假期停机') {
        return 'vacation';
    }
    else if(type=='维修停机') {
        return 'service';
    }
    else if(type=='争议停机') {
        return 'controversy';
    }
    else if(type=='自定义停机') {
        return 'custom';
    }
    else if(type=='常规停机') {
        return 'conventional';
    }else {
        return '';
    }
}

function typeLength(type) {
    if(type.length>7){
        return type.substring(0,7);
    }else{
        return type;
    }
}

var pageNum=1;

function getData(ty) {
    if(ty!='dow'){
        $('#spinner').show();
    }
    var condition=$('#searchInp').val();
    var stopType=$('.searchType ul li.active').attr('data-id')||'';

    var url='/equipment/newVersion/search';
    var mdObj=md5Fun(appUserId,url,appToken);
    $.ajax({
        type: "POST",
        timeout : 5000,
        url: webUrlCon+url,
        data: {condition:condition,stopType:stopType,indexPage:indexPage,size:10},
        beforeSend: function(request) {
            //request.setRequestHeader("Content-Type", "application/json");
            request.setRequestHeader("sequence", mdObj.sequence);
            request.setRequestHeader("nonceStr", mdObj.nonceStr);
            request.setRequestHeader("userId", appUserId);
            request.setRequestHeader("token",appToken);
            //xmlhttp.setRequestHeader("infName", url);
            //xmlhttp.setRequestHeader("osVersion", '');
            request.setRequestHeader("versionType", "0");
            request.setRequestHeader("osPlatform", mdObj.osPlatform);
            request.setRequestHeader("appVersion", mdObj.appVersion);
            request.setRequestHeader("sign", mdObj.sign);
        },
        success: function (data) {
            console.log(data)
            if(indexPage!=1){
                //layer.closeAll('loading');
            }
            if(data.code==100){
                num=data.content.num;
                pageNum=data.content.pageNum;
                var equipmentHtml='';
                if(data.content.list==''){
                    $('#scroller').hide()
                    $('.scroller').show()
                }else{
                    $('.scroller').hide()
                    $('#scroller').show()
                    var list=data.content.list;
                    for(var i=0;list.length>i;i++){
                        equipmentHtml+='<li class="red" data-id="'+list[i].id+'" data-no="'+list[i].no+'" data-departmentName="'+list[i].departmentName+'" data-modelName="'+list[i].modelName+'" data-brandName="'+list[i].brandName+'" data-systemBrand="'+list[i].systemBrand+'" data-nickcode="'+list[i].nickcode+'">' +
                            '                    <div class="conTit"><span class="spL">固定资产编号：'+list[i].no+'</span><span class="spR">停机中</span></div>' +
                            '                    <div class="conInfo">' +
                            '                        <p>设备编码：'+list[i].nickcode+'</p>' +
                            '                        <p>部门：'+list[i].departmentName+'</p>' +
                            '                        <p>类型：'+list[i].equipmentType+'</p>' +
                            '                    </div>' +
                            '                    <div class="conType">';
                        for(var j=0;list[i].stopDetailList.length>j;j++){
                            var timeDiff=list[i].stopDetailList[j].timeDiff;
                            timeDiff=timeDiff.replace(/:/,"h");
                            timeDiff=timeDiff.replace(/:/,"m");
                            var timeDiffLen=timeDiff.indexOf("m");
                            timeDiff=timeDiff.substring(0,timeDiffLen+1);
                            equipmentHtml  +=       '<span class="'+typeClass(list[i].stopDetailList[j].type)+'">'+typeLength(list[i].stopDetailList[j].type)+' '+timeDiff+'</span>';
                        }
                        equipmentHtml  +=       '</div>' +
                            '                </li>';
                    }
                }
                if(indexPage==1){
                    $('.conBoxLi').html(equipmentHtml);

                }else{
                    $('.conBoxLi').append(equipmentHtml);
                }
                if(ty!='dow'){
                    $('#spinner').hide();
                }

                document.getElementById("spinner").style.display="none";
                document.getElementById("main").style.display="block";

                document.title='设备运行('+num+'台停机)';

                if(num>10){
                    document.getElementById('pullUp').style.display='block';
                }else{
                    document.getElementById('pullUp').style.display='none';
                }

                myScroll.refresh();
            }else if(data.code==-2){
                layer.open({
                    content: data.code+' 数据故障'
                    ,btn: '确定'
                });
            }
            else{
                //fundebug.notify("equipment/searchRecord接口返回数据", JSON.stringify(data));
                layer.open({
                    content: data.code+data.message
                    ,btn: '确定'
                });
            }
        },
        error: function(e) {
            if(indexPage!=1){
                //layer.closeAll('loading');
            }
            /*layer.open({
                content: '无法请求服务器，请稍后再试！'
                ,btn: '确定'
            });*/
        }
    });
}


function getDataSea(ty) {
    if(ty!='dow'){
        $('#spinner').show();
    }
    var condition=$('#searchInp').val();
    condition=replaceIllegalStr(condition);
    var stopType=$('.searchType ul li.active').attr('data-id')||'';
    var url='/equipment/newVersion/search';
    var mdObj=md5Fun(appUserId,url,appToken);
    $.ajax({
        type: "POST",
        timeout : 5000,
        url: webUrlCon+url,
        data: {condition:condition,stopType:stopType,indexPage:indexPage,size:10},
        beforeSend: function(request) {
            //request.setRequestHeader("Content-Type", "application/json");
            request.setRequestHeader("sequence", mdObj.sequence);
            request.setRequestHeader("nonceStr", mdObj.nonceStr);
            request.setRequestHeader("userId", appUserId);
            request.setRequestHeader("token",appToken);
            //xmlhttp.setRequestHeader("infName", url);
            //xmlhttp.setRequestHeader("osVersion", '');
            request.setRequestHeader("versionType", "0");
            request.setRequestHeader("osPlatform", mdObj.osPlatform);
            request.setRequestHeader("appVersion", mdObj.appVersion);
            request.setRequestHeader("sign", mdObj.sign);
        },
        success: function (data) {
            console.log(data)
            if(indexPage!=1){
                //layer.closeAll('loading');
            }
            if(data.code==100){
                num=data.content.num;
                pageNum=data.content.pageNum;
                var equipmentHtml='';
                if(data.content.list==''){
                    $('#scroller').hide()
                    $('.scroller').show()
                }else{
                    $('.scroller').hide()
                    $('#scroller').show()
                    var list=data.content.list;
                    for(var i=0;list.length>i;i++){
                        equipmentHtml+='<li class="red" data-id="'+list[i].id+'" data-no="'+list[i].no+'" data-departmentName="'+list[i].departmentName+'" data-modelName="'+list[i].modelName+'" data-brandName="'+list[i].brandName+'" data-systemBrand="'+list[i].systemBrand+'" data-nickcode="'+list[i].nickcode+'">' +
                            '                    <div class="conTit"><span class="spL">固定资产编号：'+list[i].no+'</span><span class="spR">停机中</span></div>' +
                            '                    <div class="conInfo">' +
                            '                        <p>设备编码：'+list[i].nickcode+'</p>' +
                            '                        <p>部门：'+list[i].departmentName+'</p>' +
                            '                        <p>类型：'+list[i].equipmentType+'</p>' +
                            '                    </div>' +
                            '                    <div class="conType">';
                        for(var j=0;list[i].stopDetailList.length>j;j++){
                            var timeDiff=list[i].stopDetailList[j].timeDiff;
                            timeDiff=timeDiff.replace(/:/,"h");
                            timeDiff=timeDiff.replace(/:/,"m");
                            var timeDiffLen=timeDiff.indexOf("m");
                            timeDiff=timeDiff.substring(0,timeDiffLen+1);
                            equipmentHtml  +=       '<span class="'+typeClass(list[i].stopDetailList[j].type)+'">'+typeLength(list[i].stopDetailList[j].type)+' '+timeDiff+'</span>';
                        }
                        equipmentHtml  +=       '</div>' +
                            '                </li>';
                    }
                }
                if(indexPage==1){
                    $('.conBoxLi').html(equipmentHtml);
                }else{
                    $('.conBoxLi').append(equipmentHtml);
                }
                if(ty!='dow'){
                    $('#spinner').hide();
                }

                document.getElementById("spinner").style.display="none";
                document.getElementById("main").style.display="block";

                document.title='设备运行('+num+'台停机)';
                if(num>10){
                    pullUpEl = document.getElementById('pullUp');
                    pullUpEl.querySelector('.pullUpLabel').innerHTML = '上拉加载更多';
                    pullUpEl.className = '';
                    document.getElementById('pullUp').style.display='block';
                }else{
                    document.getElementById('pullUp').style.display='none';
                }


                myScroll.refresh();
            }else if(data.code==-2){
                layer.open({
                    content: data.code+' 数据故障'
                    ,btn: '确定'
                });
            }
            else{
                //fundebug.notify("equipment/searchRecord接口返回数据", JSON.stringify(data));
                layer.open({
                    content: data.code+data.message
                    ,btn: '确定'
                });
            }
        },
        error: function(e) {

        }
    });
}

$(document).ready(function(){
    var u = navigator.userAgent;
    if (u.indexOf('iPhone') > -1) {   //苹果手机
        setTimeout(function () {
            getTokenIos();
        },50)
        setTimeout(function () {
            getDataStopType();
            getData('');
        },100)
    }else{
        getToken();
        getDataStopType();
        getData('');
    }
    iscrol();


    /*停机类型*/
    $('.searchBut').click(function () {
        $('.searchTypeBox').show();
        $('html,body').addClass('ovfHiden');
    });
    /*$('.searchTypeBox .bj').click(function () {
        $('.searchTypeBox').hide();
    })*/

    //停机类型
    $('.searchType').on('click','li > span',function () {
        $('.searchType ul li').removeClass('active');
        $(this).parent('li').addClass('active');
    });

    //跳转停机详情
    $('.conBox').on('click','.conBoxLi li',function () {
        $('#searchInp').trigger('blur');
        localStorage.id=$(this).attr('data-id');
        localStorage.no=$(this).attr('data-no');
        localStorage.departmentName=$(this).attr('data-departmentName');
        localStorage.modelName=$(this).attr('data-modelName');
        localStorage.brandName=$(this).attr('data-brandName');
        localStorage.systemBrand=$(this).attr('data-systemBrand');
        localStorage.nickcode=$(this).attr('data-nickcode');
        if (u.indexOf('iPhone') > -1) {   //苹果手机
            location.href='searchRecord.html';
        }else {
            jsObj.openHyperLinkReference('searchRecord.html');
        }
    });

    //确认
    $('.confirm').click(function () {
        if($('.searchType li.active').length>0){
            $('.searchBut').addClass('act');
        }else{
            $('.searchBut').removeClass('act');
        }
        $('.searchTypeBox').hide();
        $('html,body').removeClass('ovfHiden');
        indexPage=1
        getData('');
    });

    //消除
    $('.eliminate').click(function () {
        $('.searchType li').removeClass('active');
        $('.searchBut').removeClass('act');
        $('.searchTypeBox').hide();
        $('html,body').removeClass('ovfHiden');
        indexPage=1
        getData('');
    });

    /* 文本框搜索 */
    $('#searchInp').focus(function () {
        //$('.cancelBut').show();
        //$('.searchLiBox').show();
        //$('.searchBut').hide();
        //$('.searchTypeBox').hide();
        $('html,body').addClass('ovfHiden');
    });
     $('.cancelBut').click(function () {
         /*$('.searchBut').show();
         $('.cancelBut').hide();
         $('.searchLiBox').hide();*/
         $('html,body').removeClass('ovfHiden');
     });
    $('.searchLi').on('click','li',function () {
        console.log($(this).html());
        $('.searchBut').show();
        $('.cancelBut').hide();
        $('.searchLiBox').hide();
        $('html,body').removeClass('ovfHiden');
    });
    var searchTimer=null;
    $('#searchInp').on('input', function(e){
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function(){
            indexPage=1;
            getDataSea('');
        }, 1300);
    });


});

function replaceIllegalStr(str) {
    var reg;
    var illegal_list = ["/", "\\",
        "[", "]",
        "{", "}",
        "<", ">",
        "＜", "＞",
        "「", "」",
        "：", "；",
        "、", "•",
        "^", "'", "\"",
        "\r", "\r\n", "\\n", "\n"];
    for (var i = 0; i < illegal_list.length; i++) {
        if (str.indexOf(illegal_list[i]) >= 0) {
            if (illegal_list[i] == '\\' || illegal_list[i] == '[') {
                reg = new RegExp('\\' + illegal_list[i], "g");
            } else {
                reg = new RegExp(illegal_list[i], "g");
            }
            str = str.replace(reg, '');
        }
    }
    return str.trim();
}

var myScroll,
    pullDownEl, pullDownOffset,
    pullUpEl, pullUpOffset;

function pullDownAction () {
    indexPage=1
    getData('dow');
}
function pullUpAction () {
    indexPage++;
    if(pageNum>=indexPage){
        getData('dow');
    }else{
        pullUpEl = document.getElementById('pullUp');
        pullUpEl.querySelector('.pullUpLabel').innerHTML = '已加载全部';
        pullUpEl.className = '';
    }

}
function iscrol() {
    pullDownEl = document.getElementById('pullDown');
    pullDownOffset = pullDownEl.offsetHeight;
    pullUpEl = document.getElementById('pullUp');
    pullUpOffset = pullUpEl.offsetHeight;

    myScroll = new iScroll("wrapper",{
        topOffset:50,
        onScrollStart:function(){
            console.log('onScrollStart');
        },
        onScrollMove:function(){
            /*console.log('onScrollMove');
            console.log('this.y='+this.y);
            console.log('this.maxScrollY='+this.maxScrollY);*/

            //头部刷新
            if (this.y > 10 && !pullDownEl.className.match('flip')) {
                pullDownEl.className = 'flip';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放刷新';
                this.minScrollY = 0;
            }
            else if (this.y < 10 && pullDownEl.className.match('flip')) {
                pullDownEl.className = '';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放刷新';
                this.minScrollY = -pullDownOffset;
            }
            else if (this.y < (this.maxScrollY - 10) && !pullUpEl.className.match('flip')) {
                pullUpEl.className = 'flip';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '释放加载更多';
                this.maxScrollY = this.maxScrollY;
            }
            else if (this.y > (this.maxScrollY + 10) && pullUpEl.className.match('flip')) {
                pullUpEl.className = '';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '释放刷新';
                this.maxScrollY = pullUpOffset;
            }
        },
        onTouchEnd:function(){
            console.log('onTouchEnd');
        },

        onScrollEnd:function(){
            console.log('onScrollEnd');

            if (pullDownEl.className.match('flip')) {
                pullDownEl.className = 'loading';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '加载中...';
                pullDownAction();
            } else if (pullUpEl.className.match('flip')) {
                pullUpEl.className = 'loading';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '加载中...';
                pullUpAction();
            }
        },
        onRefresh:function(){
            console.log('onRefresh');
            if (pullDownEl.className.match('loading')) {
                pullDownEl.className = '';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉刷新';
            } else if (pullUpEl.className.match('loading')) {
                pullUpEl.className = '';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '上拉加载更多';
            }
        }

    });

}

